package com.bawei.user

import android.content.Intent
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.mvvm.BaseActivity
import com.bawei.user.databinding.ActivityUserInfoBinding
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

@Route(path = "/user/UserInfoActivity")
class UserInfoActivity : BaseActivity<ActivityUserInfoBinding,UserViewModel>() {
    var aaa = ""
    var nnn = ""
    //
    override fun getLoutyId(): Int {
        return R.layout.activity_user_info
    }

    override fun getViewModel(): Class<UserViewModel> {
        return UserViewModel::class.java
    }

    override fun initView() {
        //请求数据
        viewModel.userInFo()

        //修改密码
        binding.btn1.setOnClickListener {
//            startActivity(Intent(this@UserInfoActivity,UpdateRwdActivity::class.java))
            ARouter.getInstance().build("/user/UpdateRwdActivity").navigation()
        }

        //
        binding.iv.setOnClickListener {
            PictureSelector.create(this,PictureSelector.SELECT_REQUEST_CODE).selectPicture()
        }

        //
        binding.updateTou.setOnClickListener {
            viewModel.edit(aaa,nnn)
        }
    }

    override fun initDate() {

        //
        viewModel.userInFoSuccess.observe(this){
            if (it.code == 200){
                //使用数据绑定形式展示
                binding.userInfo = it.data
                //保存姓名
                nnn = it.data.nickname
            }
            //
            ToastUtils.showLong(it.message)
        }

        //
        viewModel.updateSuccess.observe(this){
            if (it.code == 200){
                ToastUtils.showLong(it.data.url)
                //再次调用修改用户信息的接口
                aaa = it.data.url
            }
        }
    }

    //
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE && resultCode == RESULT_OK){
            val pictureBean = data!!.extras!!.get(PictureSelector.PICTURE_RESULT) as PictureBean
            //
            Glide.with(this).load(pictureBean.path).into(binding.iv)
            //调用接口
            var body = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), File(pictureBean.path))
            var part = MultipartBody.Part.createFormData("multipart","a.png",body)
            viewModel.update("user",part,"0")
        }
    }

}